//
//  FloatingBall.swift
//  Sample
//
//  Created by Ranki on 2025/7/12.
//  Copyright © 2025 Roy Marmelstein. All rights reserved.
//

import UIKit

class FloatingBall: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = .systemBlue
        layer.cornerRadius = 25
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowOpacity = 0.3
        layer.shadowRadius = 4
        
        // 添加拖拽手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        addGestureRecognizer(panGesture)
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        addGestureRecognizer(tapGesture)
    }
    
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: superview)
        
        switch gesture.state {
        case .changed:
            center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
            gesture.setTranslation(.zero, in: superview)
        case .ended:
            snapToEdge()
        default:
            break
        }
    }
    
    @objc private func handleTap() {
        // 处理点击事件
        print("Floating ball tapped!")
    }
    
    private func snapToEdge() {
        guard let superview = superview else { return }
        
        let screenWidth = superview.bounds.width
        let centerX = center.x
        
        let targetX: CGFloat
        if centerX < screenWidth / 2 {
            targetX = 30 // 吸附到左边
        } else {
            targetX = screenWidth - 30 // 吸附到右边
        }
        
        UIView.animate(withDuration: 0.3) {
            self.center.x = targetX
        }
    }
}
